import Taro from '@tarojs/taro';

// 环境配置
const isDev = process.env.NODE_ENV === 'development' || process.env.TARO_ENV === 'weapp';

/**
 * 支付处理器
 */
export class PaymentHandler {
  /**
   * 处理支付
   * @param orderData 订单数据
   * @returns 支付结果
   */
  static async processPayment(orderData: any): Promise<{
    success: boolean;
    data?: any;
    message: string;
  }> {
    if (isDev) {
      // 开发环境：模拟支付成功
      return this.mockPayment(orderData);
    } else {
      // 生产环境：调用真实支付接口
      return this.realPayment(orderData);
    }
  }

  /**
   * 模拟支付（开发环境）
   */
  private static async mockPayment(orderData: any): Promise<{
    success: boolean;
    data: any;
    message: string;
  }> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 模拟生成订单
    const mockOrder = {
      id: Math.floor(Math.random() * 1000) + 1,
      orderNo: `ORD${Date.now()}`,
      customerName: orderData.customerName,
      customerPhone: orderData.customerPhone,
      totalAmount: orderData.products.reduce((total: number, product: any) => 
        total + (product.price * product.quantity), 0),
      status: 'paid',
      paymentMethod: orderData.paymentMethod,
      createTime: new Date().toLocaleString('zh-CN'),
      products: orderData.products
    };

    console.log('🎯 [开发环境] 模拟支付成功:', mockOrder);

    return {
      success: true,
      data: mockOrder,
      message: '支付成功（开发环境模拟）'
    };
  }

  /**
   * 真实支付（生产环境）
   */
  private static async realPayment(orderData: any): Promise<{
    success: boolean;
    data?: any;
    message: string;
  }> {
    try {
      // 这里将调用真实的后端API
      const { createOrder } = await import('../api/order');
      const response = await createOrder(orderData);
      return {
        success: response.isSuccess,
        data: response.data,
        message: response.message
      };
    } catch (error) {
      console.error('支付失败:', error);
      return {
        success: false,
        message: '支付失败，请重试'
      };
    }
  }

  /**
   * 调用微信支付
   * @param payParams 支付参数
   */
  static async wxPay(payParams: any): Promise<boolean> {
    if (isDev) {
      // 开发环境：模拟微信支付成功
      console.log('🎯 [开发环境] 模拟微信支付调用:', payParams);
      
      Taro.showToast({
        title: '模拟支付成功',
        icon: 'success',
        duration: 1500
      });
      
      return true;
    } else {
      // 生产环境：调用真实微信支付
      return new Promise((resolve) => {
        Taro.requestPayment({
          ...payParams,
          success: () => {
            console.log('微信支付成功');
            resolve(true);
          },
          fail: (err) => {
            console.error('微信支付失败:', err);
            Taro.showToast({
              title: '支付失败',
              icon: 'error'
            });
            resolve(false);
          }
        });
      });
    }
  }
}

/**
 * 获取当前环境
 */
export function getCurrentEnv(): 'development' | 'production' {
  return isDev ? 'development' : 'production';
}

/**
 * 显示环境提示
 */
export function showEnvTip(): void {
  if (isDev) {
    console.log('🚀 当前运行在开发环境，支付功能已模拟');
    Taro.showToast({
      title: '开发环境模拟支付',
      icon: 'none',
      duration: 2000
    });
  }
}
